print('[kkbt] Start Update')

-- 加载os模块
local os = os

-- 定义MD文件的URL
local md_url = ""

-- 使用wget下载MD文件

local wgetCommand = [[
rm -rf ./content/kkbt/sum.json
rm -rf ./content/kkbt/sum.md
wget -O ./content/kkbt/sum.json https://note.ftls.xyz/help/kkbt-sum.md &
wget -O ./content/kkbt/sum.md https://note.ftls.xyz/sum-kkbt.md &
wait
]]
print('[kkbt] Command: ')
print(wgetCommand)
print('[kkbt] Run: ')
os.execute('sh -c "' .. wgetCommand .. '"')
print('[kkbt] Finish Read Index')
print('[kkbt] Updating ... ')

local json = require("script/json")
local function readJson(path)
    local file = io.open(path, 'r')
    if file then
        local content = file:read("*a")
        file:close()
        return json.decode(content)
    end
end

-- 读取 json文件
local file = io.open('./content/kkbt/sum.json', 'r')

local oldFiles = readJson('./content/kkbt/sum.old.json')
local nowFiles = readJson('./content/kkbt/sum.json')
    -- for _, url in ipairs(jsonArr) do
    --     print(url["path"], url["mtime"])
    -- end

local oldMap = {}
for _, file in ipairs(oldFiles) do
    oldMap[file.path] = file
end

local nowMap = {}
for _, file in ipairs(nowFiles) do
    nowMap[file.path] = file
end

local deleted = {}
local modified = {}
local added = {}

-- Find deleted and modified files
for path, oldFile in pairs(oldMap) do
    local nowFile = nowMap[path]
    if nowFile == nil then
        table.insert(deleted, oldFile)
    -- elseif nowFile.mtime ~= oldFile.mtime then
    elseif (nowFile.mtime ~= oldFile.mtime) and (nowFile.size ~= oldFile.size) then
        table.insert(modified, {path = path, old_mtime = oldFile.mtime, new_mtime = nowFile.mtime})
    end
end

-- Find added files
for path, nowFile in pairs(nowMap) do
    if oldMap[path] == nil then
        table.insert(added, nowFile)
    end
end

local commandStr = ""
local sumText = ""

-- Print results
print("Deleted files:")
for _, file in ipairs(deleted) do
    print(file.path)
    local command = 'rm -rf ./content/' .. file.path .. '\n'
    commandStr = commandStr .. '\n' .. command
end

print("\nModified files:")
for _, file in ipairs(modified) do
    print(file.path, "old mtime:", file.old_mtime, "new mtime:", file.new_mtime)
    local command1 = 'rm -rf ./content/' .. file.path .. '\n'
    local command2 = 'wget -P ./content/'..file.path:match("(.*/)")..' https://note.ftls.xyz/' .. file.path..' &'
    commandStr = commandStr .. '\n' .. command1 .. '\n' .. command2
end

print("\nAdded files:")
for _, file in ipairs(added) do
    print(file.path)
    local command = 'wget -P ./content/'..file.path:match("(.*/)")..' https://note.ftls.xyz/' .. file.path..' &'
    commandStr = commandStr .. '\n' .. command
end

print('[kkbt] Update Command: ')
commandStr = commandStr .. '\n' .. 'wait'
print(commandStr)
print('[kkbt] Run: ')
os.execute('sh -c "' .. commandStr .. '"')
os.execute('cp ./content/kkbt/sum.json ./content/kkbt/sum.old.json')
print('[kkbt] Finish Update')


-- 定义trim函数
local function trim(s)
    return (s:gsub("^%s+", "")):gsub("%s+$", "")
end

-- 定义trim函数
local function trim2(s)
    return (s:gsub("^%s*(.-)%s*$", "%1"))
end

-- 打开文件
local file = io.open('./content/kkbt/sum.md', 'r')
if file then
    -- 读取文件
    local lines = {}
    for line in file:lines() do
        table.insert(lines, line)
    end
    file:close()

    -- 处理每一行
    for i, line in ipairs(lines) do
        line = trim(line)
        line = string.sub(line, 1, string.len(line) - 3)
        line = '[[' .. line .. ']]'
        lines[i] = line
    end

    -- 保存文件
    local new_file = io.open('./content/kkbt/sum.md', 'w')
    if new_file then
        new_file:write('**目录:**\n{{< tree >}}\n\n**索引列表:**\n')
        for _, line in ipairs(lines) do
            new_file:write(line .. '\n')
        end
        new_file:write('\n\n'..os.date("%Y-%m-%d %H:%M",os.time() + (8 * 60 * 60))..' 构建\n')
        new_file:close()
    end
end